<template>
  <div class="app-container">
    <el-row>
      <!--区域数据-->
      <el-col :xs="24" v-show="treeVisibale === true" class="tree_bg">
        <!-- <div>
          <el-input
            v-model="keyWordName"
            placeholder="输入关键字进行过滤"
            clearable
            size="small"
            prefix-icon="el-icon-search"
            style="margin-bottom: 20px"
          />
        </div> -->
        <div class="head-container">
          <el-tree
            :data="areaOptions"
            :props="defaultProps"
            :expand-on-click-node="false"
            :filter-node-method="filterNode"
            ref="tree"
            node-key="id"
            default-expand-all
            highlight-current
            @node-click="handleNodeClick"
          />
        </div>
        <div class="tree_close" @click="changeTreeShow">
          <i class="el-icon-caret-left" style="color: white"></i>
        </div>
      </el-col>
      <el-col class="jiange"></el-col>
      <div class="tree_open" @click="changeTreeShow" v-show="treeVisibale === false">
        <i class="el-icon-caret-right" style="color: white"></i>
      </div>
      <el-col :xs="24" :class="treeVisibale ? 'table_small_bg' : 'table_big_bg'">
        <el-row class="line-bottom" v-show="showSearch">
          <el-col class="form_col">
            <el-form :model="queryParams" ref="queryForm" :size="size" v-show="showSearch" label-width="90px">
              <div id="searchFilter" :gutter="10" style="display: flex; flex-wrap: wrap">
<!--                <el-form-item label="区域编号" prop="AreaCode">-->
<!--                  <el-input-->
<!--                    v-model="queryParams.AreaCode"-->
<!--                    placeholder="请输入区域编号"-->
<!--                    clearable-->
<!--                    @keyup.enter.native="handleQuery"-->
<!--                    class="input_w"-->
<!--                  />-->
<!--                </el-form-item>-->
                <el-form-item label="设备编号" prop="TerminalID">
                  <el-input
                    v-model="queryParams.TerminalID"
                    placeholder="请输入设备编号"
                    clearable
                    @keyup.enter.native="handleQuery"
                  />
                </el-form-item>
                <el-form-item label="设备名称" prop="TerminalName">
                  <el-input
                    v-model="queryParams.TerminalName"
                    placeholder="请输入设备名称"
                    clearable
                    @keyup.enter.native="handleQuery"
                  />
                </el-form-item>
                <el-form-item label="通讯地址" prop="communicateAddress">
                  <el-input
                    v-model="queryParams.communicateAddress"
                    placeholder="请输入通讯地址"
                    clearable
                    @keyup.enter.native="handleQuery"
                  />
                </el-form-item>
                <el-form-item label="表状态" prop="TerminalMark">
                  <el-select v-model="queryParams.TerminalMark" placeholder="请选择表状态" style="width: 100%" clearable>
                    <el-option v-for="item of Terminalmark" :key="item.value" :label="item.label"
                              :value="item.value"></el-option>
                  </el-select>
                </el-form-item>
                <el-form-item>
                </el-form-item>
              </div>
            </el-form>
          </el-col>
          <el-col class="form_query">
            <el-button v-show="collapseAble" type="text" @click="shiftCollapseAble" class="text">
              <span>
                {{ fold ? '收起筛选' : '更多筛选' }}
              </span>
            </el-button>
            <el-button type="primary" @click="handleQuery" size="mini">查询</el-button>
            <el-button @click="resetQuery" size="mini">重置</el-button>
          </el-col>
        </el-row>
        <el-row :gutter="10" class="mb8 padding_top_bottom">
          <el-col :span="1.5">
            <el-button
              type="primary"
              plain
              icon="el-icon-plus"
              size="mini"
              @click="handleAdd"
              v-hasPermi="['basedata:terminalsdb:add']"
            >新增</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button
              type="info"
              plain
              icon="el-icon-upload2"
              size="mini"
              @click="handleImport"
            >导入</el-button>
          </el-col>
          <!-- <el-button
            type="text"
            size="small"
            icon="el-icon-view"
            @click="handlePreview(scope.row)"
          >预览</el-button> -->
          <!-- v-hasPermi="['tool:gen:import']" -->
          <!-- <el-col :span="1.5">
            <el-button
              type="primary"
              plain
              icon="el-icon-edit"
              size="mini"
              :disabled="single"
              @click="handleUpdate"
              v-hasPermi="['basedata:terminalsdb:edit']"
            >修改</el-button>
          </el-col> -->
          <el-col :span="1.5">
            <el-button
              type="danger"
              plain
              icon="el-icon-delete"
              size="mini"
              :disabled="multiple"
              @click="handleDelete"
              v-hasPermi="['basedata:terminalsdb:remove']"
            >批量删除</el-button>
          </el-col>
<!--           <el-col :span="1.5">-->
<!--            <el-button-->
<!--              type="warning"-->
<!--              plain-->
<!--              icon="el-icon-download"-->
<!--              size="mini"-->
<!--              @click="handleExport"-->
<!--              v-hasPermi="['basedata:terminalsdb:export']"-->
<!--            >导出</el-button>-->
<!--          </el-col>-->
          <RightDropdown :columns="columns" :showSearch.sync="showSearch" @queryTable="getList" @export="handleExport" :hasPermiExport="['basedata:terminalsdb:export']"></RightDropdown>
        </el-row>

        <el-table v-loading="loading" :data="terminalsdbList" @selection-change="handleSelectionChange" max-height="600px"  ref="tableList">
          <el-table-column type="selection" width="55" align="center" fixed :selectable="selectable"/>
          <!-- <el-table-column label="自增主键" align="center" prop="ID" v-if="false" :show-overflow-tooltip="true"/>
          <el-table-column label="设备归属水司" align="center" prop="tenantId" v-if="false" :show-overflow-tooltip="true" width="120"/> -->
          <el-table-column label="区域编号" align="center" prop="AreaCode" v-if="columns[0].visible" :show-overflow-tooltip="true"/>
          <el-table-column label="楼栋编号" align="center" prop="ldId" v-if="columns[1].visible" :show-overflow-tooltip="true"/>
          <el-table-column label="房间号" align="center" prop="roomId" v-if="columns[2].visible" :show-overflow-tooltip="true"/>
          <el-table-column label="设备名称" align="center" prop="TerminalName" v-if="columns[3].visible" :show-overflow-tooltip="true" width="150"/>
          <el-table-column label="设备编号" align="center" prop="TerminalID" v-if="columns[4].visible" :show-overflow-tooltip="true" width="150"/>
          <el-table-column label="用户编号" align="center" prop="UserID" v-if="columns[5].visible" :show-overflow-tooltip="true" width="150"/>
          <el-table-column label="表状态" align="center" prop="TerminalMark" v-if="columns[6].visible" :show-overflow-tooltip="true">
            <template slot-scope="scope">
              <dict-tag :options="dict.type.used_status" :value="scope.row.TerminalMark"/>
            </template>
          </el-table-column>
          <el-table-column label="表型号" align="center" prop="TypeID" v-if="columns[7].visible" :show-overflow-tooltip="true" width="180">
            <template slot-scope="scope">
              <dict-tag :options="dict.type.module_type" :value="scope.row.TypeID"/>
            </template>
          </el-table-column>
          <el-table-column label="表底数" align="center" prop="BaseReading" v-if="columns[8].visible" :show-overflow-tooltip="true"/>
          <el-table-column label="厂家名称" align="center" prop="SupplierID" v-if="columns[9].visible" :show-overflow-tooltip="true" width="120">
            <template slot-scope="scope">
              <dict-tag :options="dict.type.terminal_supplier" :value="scope.row.SupplierID"/>
            </template>
          </el-table-column>
          <el-table-column label="安装日期" align="center" prop="InstallDate" v-if="columns[10].visible" :show-overflow-tooltip="true"  width="120">
            <template slot-scope="scope">
              <span>{{ parseTime(scope.row.InstallDate, '{y}-{m}-{d}') }}</span>
            </template>
          </el-table-column>
          <el-table-column label="安装地址" align="center" prop="InstallAddress" v-if="columns[11].visible" :show-overflow-tooltip="true" width="180"/>
          <el-table-column label="IMEI" align="center" prop="IMEI" v-if="columns[12].visible" :show-overflow-tooltip="true"/>
          <el-table-column label="SIM卡类型" align="center" prop="SIMtype" v-if="columns[13].visible" :show-overflow-tooltip="true" width="120"/>
          <el-table-column label="SIM卡号" align="center" prop="SIMNUM" v-if="columns[14].visible" :show-overflow-tooltip="true"/>
          <el-table-column label="钢印/塑封号" align="center" prop="PlasticSealNo" v-if="columns[15].visible" :show-overflow-tooltip="true" width="120"/>
          <el-table-column label="出厂编号" align="center" prop="FirstSupplierID" v-if="columns[16].visible" :show-overflow-tooltip="true" width="130"/>
          <el-table-column label="是否带阀控" align="center" prop="ValveControl" v-if="columns[17].visible" :show-overflow-tooltip="true" width="120">
            <template slot-scope="scope">
              <dict-tag :options="dict.type.yes_no" :value="scope.row.ValveControl"/>
            </template>
          </el-table-column>
          <el-table-column label="阀门地址" align="center" prop="ValveAddress" v-if="columns[18].visible" :show-overflow-tooltip="true"/>
          <!-- <el-table-column label="月冻结日期" align="center" prop="freezedateMonth" v-if="columns[19].visible" :show-overflow-tooltip="true" width="120"/> -->
          <el-table-column label="出厂日期" align="center" prop="ManufactureDate" v-if="columns[19].visible" :show-overflow-tooltip="true">
            <template slot-scope="scope">
              <span>{{ parseTime(scope.row.ManufactureDate, '{y}-{m}-{d}') }}</span>
            </template>
          </el-table-column>
          <el-table-column label="口径大小" align="center" prop="Caliber" v-if="columns[20].visible" :show-overflow-tooltip="true" width="100">
            <template slot-scope="scope">
              <dict-tag :options="dict.type.ldbd_pipe_caliber" :value="scope.row.Caliber"/>
            </template>
          </el-table-column>
          <el-table-column label="采集频率(分钟)" align="center" prop="ReadingFrequency" v-if="columns[21].visible" :show-overflow-tooltip="true" width="120"/>
          <el-table-column label="上传频率(分钟)" align="center" prop="UpFrequency" v-if="columns[22].visible" :show-overflow-tooltip="true" width="120"/>
          <el-table-column label="用户类型" align="center" prop="UserType" v-if="columns[23].visible" :show-overflow-tooltip="true"/>
          <el-table-column label="备注" align="center" prop="ReMark" v-if="columns[24].visible" :show-overflow-tooltip="true"/>
          <el-table-column label="位置识别编号" align="center" prop="locationNb" v-if="columns[25].visible" :show-overflow-tooltip="true" width="120"/>
          <el-table-column label="协议" align="center" prop="protocolName" v-if="columns[26].visible" :show-overflow-tooltip="true" width="180"/>
          <el-table-column label="通讯地址" align="center" prop="communicateAddress" v-if="columns[27].visible" :show-overflow-tooltip="true" width="180"/>
          <el-table-column label="经度" align="center" prop="lng" v-if="columns[28].visible" :show-overflow-tooltip="true" width="180"/>
          <el-table-column label="纬度" align="center" prop="lat" v-if="columns[29].visible" :show-overflow-tooltip="true" width="180"/>
          <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="160" fixed="right">
            <template slot-scope="scope">
              <el-button
                size="mini"
                type="text"
                icon="el-icon-edit"
                @click="handleUpdate(scope.row)"
                v-hasPermi="['basedata:terminalsdb:edit']"
                v-if="scope.row.TerminalMark === 1"
              >修改</el-button>
              <el-button
                size="mini"
                type="text"
                icon="el-icon-delete"
                @click="handleDelete(scope.row)"
                v-hasPermi="['basedata:terminalsdb:remove']"
                v-if="scope.row.TerminalMark === 1"
              >删除</el-button>
              <el-button
                size="mini"
                type="text"
                icon="el-icon-sort"
                @click="handlereplace(scope.row)"
                v-if="scope.row.TerminalMark === 1"
              >换表</el-button>
              <el-button
                size="mini"
                type="text"
                icon="el-icon-circle-close"
                style="color: #f5222d"
                v-if="scope.row.TerminalMark === 0"
              >已停用</el-button>
            </template>
          </el-table-column>
        </el-table>

        <pagination
          v-show="total>0"
          :total="total"
          :page.sync="queryParams.pageNum"
          :limit.sync="queryParams.pageSize"
          @pagination="getList"
        />

      </el-col>
    </el-row>

    <!-- 添加或修改大档案对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="750px" append-to-body class="container-box">
      <el-form ref="form" :model="form" :rules="rules" :label-width="labelWidth" :inline="true">
        <!-- <el-form-item label="归属水司" prop="tenantId">
          <el-input v-model="form.tenantId" placeholder="请输入归属水司" disabled/>
        </el-form-item> -->
        <el-form-item label="协议" prop="protocolId">
          <el-select v-model="form.protocolId" placeholder="请选择协议" style="width: 202px;">
            <el-option v-for="protocolItem in protocolOption" :key="protocolItem.protocolId" :label="protocolItem.protocolName" :value="protocolItem.protocolId"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="区域名称" prop="AreaCode">
          <!-- <el-select v-model="form.AreaCode" placeholder="请输入区域编码" style="width: 202px;">
            <el-input
              v-model="AreaName"
              placeholder="输入关键字进行过滤"
              clearable
              size="small"
              style="width: 80%; margin-left: 10%;"
            />
            <el-option class="option" :value="selectOptions.value" :label="selectOptions.label">
              <el-tree
                :data="areaOptions"
                :props="defaultProps"
                :expand-on-click-node="false"
                :filter-node-method="filterNode"
                ref="areatree"
                node-key="id"
                default-expand-all
                highlight-current
                @node-click="handleSelectTree"
                class="tree"
              />
            </el-option>
          </el-select> -->
          <treeselect v-model="form.AreaCode" :options="areaOptions" :normalizer="normalizer" :show-count="true" placeholder="请选择区域名称" style="width:202px;"/>
        </el-form-item>
<!--        <el-form-item label="楼栋编号" prop="ldId">-->
<!--          <el-input v-model="form.ldId" placeholder="请输入楼栋编号" />-->
<!--        </el-form-item>-->
<!--        <el-form-item label="房间号" prop="roomId">-->
<!--          <el-input v-model="form.roomId" placeholder="请输入房间号" />-->
<!--        </el-form-item>-->
        <el-form-item label="厂家名称" prop="SupplierID">
          <el-select v-model="form.SupplierID" filterable  placeholder="请输入厂家名称" style="width: 202px;">
            <el-option
              v-for="dict in dict.type.terminal_supplier"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="用户名称" prop="UserID">
          <el-select v-model="form.UserID" filterable  placeholder="请输入用户名称" style="width: 202px;">
            <el-option v-for="item in usersoptions" :key="item.UserID" :label="item.UserName" :value="item.UserID"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="表型号" prop="TypeID">
          <el-select v-model="form.TypeID" filterable  placeholder="请选择表型号" style="width: 202px;">
            <el-option
              v-for="dict in dict.type.module_type"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="设备名称" prop="TerminalName">
          <el-input v-model="form.TerminalName" placeholder="请输入设备名称" />
        </el-form-item>
        <el-form-item label="设备编号" prop="TerminalID">
          <el-input v-model="form.TerminalID" placeholder="请输入设备编号" />
        </el-form-item>
        <el-form-item label="表底数" prop="BaseReading">
          <el-input v-model="form.BaseReading" placeholder="请输入表底数" />
        </el-form-item>
        <el-form-item label="通讯地址" prop="communicateAddress">
          <el-input v-model="form.communicateAddress" placeholder="请输入通讯地址" />
        </el-form-item>
        <el-form-item label="安装日期" prop="InstallDate">
          <el-date-picker clearable
            v-model="form.InstallDate"
            type="date"
            value-format="yyyy-MM-dd"
            placeholder="请选择安装日期"
            style="width: 202px;">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="安装地址" prop="InstallAddress">
          <el-input v-model="form.InstallAddress" placeholder="请输入安装地址" />
        </el-form-item>
        <el-form-item label="IMEI" prop="IMEI">
          <el-input v-model="form.IMEI" placeholder="请输入IMEI" />
        </el-form-item>
        <el-form-item label="SIM卡号" prop="SIMNUM">
          <el-input v-model="form.SIMNUM" placeholder="请输入SIM卡号" />
        </el-form-item>
        <el-form-item label="钢印/塑封号" prop="PlasticSealNo">
          <el-input v-model="form.PlasticSealNo" placeholder="请输入钢印/塑封号" />
        </el-form-item>
        <el-form-item label="出厂编号" prop="FirstSupplierID">
          <el-input v-model="form.FirstSupplierID" placeholder="请输入出厂编号" />
        </el-form-item>
        <el-form-item label="是否带阀控" prop="ValveControl">
          <el-select v-model="form.ValveControl" placeholder="请选择是否带阀控" style="width: 202px;">
            <el-option v-for="dict in dict.type.yes_no" :key="dict.value" :label="dict.label" :value="parseInt(dict.value)"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="阀门地址" prop="ValveAddress">
          <el-input v-model="form.ValveAddress" placeholder="请输入阀门地址" />
        </el-form-item>
        <el-form-item label="出厂日期" prop="ManufactureDate">
          <el-date-picker clearable
            v-model="form.ManufactureDate"
            type="date"
            value-format="yyyy-MM-dd"
            placeholder="请选择出厂日期"
            style="width: 202px;">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="口径大小" prop="Caliber">
          <el-select v-model="form.Caliber" placeholder="请选择口径" style="width: 202px;">
            <el-option
              v-for="dict in dict.type.ldbd_pipe_caliber"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value.toString()"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="采集频率(分钟)" prop="ReadingFrequency">
          <el-input v-model="form.ReadingFrequency" placeholder="请输入采集频率" />
        </el-form-item>
        <el-row>
          <el-form-item label="经度" prop="lng">
            <el-input v-model="form.lng" placeholder="请点击图标获取" />
          </el-form-item>
          <el-form-item label="纬度" prop="lat">
            <el-input v-model="form.lat" placeholder="请点击图标获取" />
          </el-form-item>
          <el-form-item>
            <i class="el-icon-location-information" style="color: #1890ff" @click="handleMap"></i>
          </el-form-item>
        </el-row>
        <el-form-item label="上传频率(分钟)" prop="UpFrequency">
          <el-input v-model="form.UpFrequency" placeholder="请输入上传频率" />
        </el-form-item>
        <el-form-item label="备注" prop="ReMark">
          <el-input v-model="form.ReMark" placeholder="请输入备注" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
    <el-dialog :title="upload.title" :visible.sync="upload.open" width="400px" append-to-body >
      <el-upload
        ref="upload"
        :limit="1"
        accept=".xlsx, .xls"
        :headers="upload.headers"
        :action="upload.url + '?updateSupport=' + upload.updateSupport"
        :disabled="upload.isUploading"
        :on-progress="handleFileUploadProgress"
        :on-success="handleFileSuccess"
        :auto-upload="false"
        drag
      >
        <i class="el-icon-upload"></i>
        <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
        <div class="el-upload__tip text-center" slot="tip">
          <div class="el-upload__tip" slot="tip">
            <el-checkbox v-model="upload.updateSupport" /> 是否更新已经存在的用户数据
          </div>
          <span>仅允许导入xls、xlsx格式文件。</span>
          <!-- <el-link type="primary" :underline="false" style="font-size:12px;vertical-align: baseline;" @click="importTemplate">下载模板</el-link> -->
        </div>
      </el-upload>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitFileForm">确 定</el-button>
        <el-button @click="upload.open = false">取 消</el-button>
      </div>
    </el-dialog>
    <!-- 更换大档案对话框 -->
    <el-dialog :title="title" :visible.sync="openreplace" width="750px" append-to-body class="container-box">
      <el-form ref="form" :model="form" :rules="rules" :label-width="labelWidth" :inline="true">
        <!-- <el-form-item label="归属水司" prop="tenantId" >
          <el-input v-model="form.tenantId" placeholder="请输入归属水司" disabled/>
        </el-form-item> -->
        <el-form-item label="协议" prop="protocolId">
          <el-select v-model="form.protocolId" placeholder="请选择协议" style="width: 202px;">
            <el-option v-for="protocolItem in protocolOption" :key="protocolItem.protocolId" :label="protocolItem.protocolName" :value="protocolItem.protocolId">{{protocolItem.protocolName}}</el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="区域名称" prop="AreaCode">
          <!-- <el-select v-model="form.AreaCode" placeholder="请输入区域编码" style="width: 202px;">
            <el-input
              v-model="AreaName"
              placeholder="输入关键字进行过滤"
              clearable
              size="small"
              style="width: 80%;margin-left: 10%;"
            />
            <el-option class="option" :value="selectOptions.value" :label="selectOptions.label">
              <el-tree
                :data="areaOptions"
                :props="defaultProps"
                :expand-on-click-node="false"
                :filter-node-method="filterNode"
                ref="areatree"
                node-key="id"
                default-expand-all
                highlight-current
                @node-click="handleSelectTree"
                class="tree"
              />
            </el-option>
          </el-select> -->
          <treeselect v-model="form.AreaCode" :options="areaOptions" :normalizer="normalizer" :show-count="true" placeholder="请选择区域名称" style="width:202px;"/>
        </el-form-item>
        <el-form-item label="厂家名称" prop="SupplierID">
          <el-select v-model="form.SupplierID" filterable  placeholder="请输入厂家名称" style="width: 202px;">
            <el-option
              v-for="dict in dict.type.terminal_supplier"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="用户名称" prop="UserID">
          <el-select v-model="form.UserID" filterable  placeholder="请输入用户名称" style="width: 202px;">
            <el-option v-for="item in usersoptions" :key="item.UserID" :label="item.UserName" :value="item.UserID"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="表型号" prop="TypeID">
          <el-select v-model="form.TypeID" filterable  placeholder="请选择表型号" style="width: 202px;">
            <el-option
              v-for="dict in dict.type.module_type"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="设备名称" prop="TerminalName">
          <el-input v-model="form.TerminalName" placeholder="请输入设备名称" />
        </el-form-item>
        <el-form-item label="旧设备编号" prop="TerminalID">
          <el-input v-model="form.TerminalID" placeholder="请输入旧设备编号" :disabled="true"/>
        </el-form-item>
        <el-form-item label="新设备编号" prop="TerminalIDNew">
          <el-input v-model="form.TerminalIDNew" placeholder="请输入新设备编号" />
        </el-form-item>
        <el-form-item label="旧表底数" prop="BaseReading">
          <el-input v-model="form.BaseReading" placeholder="请输入旧表底数"/>
        </el-form-item>
        <el-form-item label="新表底数" prop="BaseReadingNew">
          <el-input v-model="form.BaseReadingNew" placeholder="请输入新表底数" />
        </el-form-item>
        <el-form-item label="旧IMEI" prop="IMEI">
          <el-input v-model="form.IMEI" placeholder="请输入旧IMEI" :disabled="true"/>
        </el-form-item>
        <el-form-item label="新IMEI" prop="IMEINew">
          <el-input v-model="form.IMEINew" placeholder="请输入新IMEI" />
        </el-form-item>
        <el-form-item label="安装日期" prop="InstallDate">
          <el-date-picker clearable
            v-model="form.InstallDate"
            type="date"
            value-format="yyyy-MM-dd"
            placeholder="请选择安装日期"
            style="width: 202px;">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="安装地址" prop="InstallAddress">
          <el-input v-model="form.InstallAddress" placeholder="请输入安装地址" />
        </el-form-item>
        <el-form-item label="通讯地址" prop="communicateAddress">
          <el-input v-model="form.communicateAddress" placeholder="请输入通讯地址" />
        </el-form-item>
        <el-form-item label="SIM卡号" prop="SIMNUM">
          <el-input v-model="form.SIMNUM" placeholder="请输入SIM卡号" />
        </el-form-item>
        <el-form-item label="钢印/塑封号" prop="PlasticSealNo">
          <el-input v-model="form.PlasticSealNo" placeholder="请输入钢印/塑封号" />
        </el-form-item>
        <el-form-item label="出厂编号" prop="FirstSupplierID">
          <el-input v-model="form.FirstSupplierID" placeholder="请输入出厂编号" />
        </el-form-item>
        <el-form-item label="是否带阀控" prop="ValveControl">
          <el-select v-model="form.ValveControl" placeholder="请选择是否带阀控" style="width: 202px;">
            <el-option v-for="dict in dict.type.yes_no" :key="dict.value" :label="dict.label" :value="parseInt(dict.value)"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="阀门地址" prop="ValveAddress">
          <el-input v-model="form.ValveAddress" placeholder="请输入阀门地址" />
        </el-form-item>
        <!-- <el-form-item label="月冻结日期" prop="freezedateMonth">
          <el-input v-model="form.freezedateMonth" placeholder="请输入月冻结日期" />
        </el-form-item> -->
        <el-form-item label="出厂日期" prop="ManufactureDate">
          <el-date-picker clearable
            v-model="form.ManufactureDate"
            type="date"
            value-format="yyyy-MM-dd"
            placeholder="请选择出厂日期"
            style="width: 202px;">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="口径大小" prop="Caliber">
          <el-select v-model="form.Caliber" placeholder="请选择口径" style="width: 202px;">
            <el-option
              v-for="dict in dict.type.ldbd_pipe_caliber"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value.toString()"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="采集频率(分钟)" prop="ReadingFrequency">
          <el-input v-model="form.ReadingFrequency" placeholder="请输入采集频率" />
        </el-form-item>
        <el-form-item label="上传频率(分钟)" prop="UpFrequency">
          <el-input v-model="form.UpFrequency" placeholder="请输入上传频率" />
        </el-form-item>
        <el-row>
          <el-form-item label="经度" prop="lng">
            <el-input v-model="form.lng" placeholder="请点击图标获取" />
          </el-form-item>
          <el-form-item label="纬度" prop="lat">
            <el-input v-model="form.lat" placeholder="请点击图标获取" />
          </el-form-item>
          <el-form-item>
            <i class="el-icon-location-information" style="color: #1890ff" @click="handleMap"></i>
          </el-form-item>
        </el-row>
        <el-form-item label="备注" prop="ReMark">
          <el-input v-model="form.ReMark" placeholder="请输入备注" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitReplace">确 定</el-button>
        <el-button @click="oncancel">取 消</el-button>
      </div>
    </el-dialog>
    <!-- 定位对话框 -->
    <!-- <MapDialog :dialogTitle="map.title" :dialogVisible="map.open" @isClose="isClose" @change="mapChange"></MapDialog> -->
    <!-- 定位对话框 -->
    <el-dialog
      width="700px"
      :title="mapdialog.title"
      :visible.sync="mapdialog.open"
      append-to-body
      @close="closeMapDialog"
      :destroy-on-close="true">
      <el-row class="line">
        <el-card shadow="never">
          <div id="mapContent" ref="mapContent"></div>
        </el-card>
      </el-row>
      <div slot="footer" class="dialog-footer">
        <!-- <el-button type="success" @click="initMap">获取当前位置</el-button> -->
        <el-button type="primary" @click="submitMap">确定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listTerminalsdb, getTerminalsdb, delTerminalsdb, addTerminalsdb, updateTerminalsdb, replaceTerminalsdb } from "@/api/record/terminalsdb";
import { getAllUsersdb } from '@/api/record/usersdb'
import { listUser, getUser, delUser, addUser, updateUser, resetUserPwd, changeUserStatus, deptTreeSelect } from "@/api/system/user";
import { getToken } from "@/utils/auth";
import { gcj2bdString } from "@/utils/coordinate";
import "highlight.js/styles/github-gist.css";
import { selectProtocol } from '@/api/basedata/protocol.js'
import Treeselect from "@riophae/vue-treeselect";
// import MapDialog from '../component/mapDialog.vue'
import "@riophae/vue-treeselect/dist/vue-treeselect.css";

export default {
  name: "Terminalsdb",
  dicts: ['warnparamtype', 'terminal_supplier', 'used_status', 'warntargettype', 'belongDepartment', 'module_type','ldbd_pipe_caliber','yes_no', 'default_position'],
  components: { Treeselect },
  data() {
    return {
      // 导入参数
      upload: {
        // 是否显示弹出层（用户导入）
        open: false,
        // 弹出层标题（用户导入）
        title: "",
        // 是否禁用上传
        isUploading: false,
        // 是否更新已经存在的用户数据
        updateSupport: 0,
        // 设置上传的请求头部
        headers: { Authorization: "Bearer " + getToken() },
        // 上传的地址
        url: process.env.VUE_APP_BASE_API + "/basedata/terminalsdb/importData"
      },
      selectOptions:{},
      size:'small',
      collapseAble: false,
      fold: false,
      maxShow: '4',
      labelWidth: '120px',
      // 列信息
      columns: [
        // { key: 0, label: `自增主键`, visible: false },
        // { key: 1, label: `设备归属水司`, visible: false },
        { key: 0, label: `区域编号`, visible: false },
        { key: 1, label: `楼栋编号`, visible: false },
        { key: 2, label: `房间号`, visible: false },
        { key: 3, label: `设备名称`, visible: true },
        { key: 4, label: `设备编号`, visible: true },
        { key: 5, label: `用户编号`, visible: true },
        { key: 6, label: `表状态`, visible: true },
        { key: 7, label: `表型号`, visible: true },
        { key: 8, label: `表底数`, visible: false },
        { key: 9, label: `厂家名称`, visible: true },
        { key: 10, label: `安装日期`, visible: true },
        { key: 11, label: `安装地址`, visible: true },
        { key: 12, label: `IMEI`, visible: true },
        { key: 13, label: `SIM卡类型`, visible: false },
        { key: 14, label: `SIM卡号`, visible: true },
        { key: 15, label: `钢印号`, visible: true },
        { key: 16, label: `出厂编号`, visible: true },
        { key: 17, label: `是否带阀控`, visible: true },
        { key: 18, label: `阀门地址`, visible: false },
        // { key: 19, label: `月冻结日期`, visible: false },
        { key: 19, label: `出厂日期`, visible: false },
        { key: 20, label: `口径`, visible: true },
        { key: 21, label: `采集频率(分钟)`, visible: true },
        { key: 22, label: `上传频率(分钟)`, visible: true },
        { key: 23, label: `用户类型`, visible: false },
        { key: 24, label: `备注`, visible: false },
        { key: 25, label: `位置识别编号`, visible: false },
        { key: 26, label: `协议`, visible: true },
        { key: 27, label: `通讯地址`, visible: true },
        { key: 28, label: `经度`, visible: true },
        { key: 29, label: `纬度`, visible: true },
      ],
      defaultProps: {
        children: "children",
        label: "label"
      },
      Terminalmark: [
        {label: '全部', value: null},
        {label: '正常', value: 1},
        {label: '停用', value: 0},
      ],
      // 区域树选项
      areaOptions: [],
      // 用户选项
      usersoptions: [],
      // 区域名称
      keyWordName: undefined,
      // 树状态
      treeVisibale: true,
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      terminalids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 大档案表格数据
      terminalsdbList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      openreplace: false,
      // 协议下拉框中的数据
      protocolOption: [],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 20,
        AreaCode: null,
        TerminalID: null,
        TerminalName: null,
        communicateAddress: null,
        TerminalMark: 1,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        // tenantId: [
        //   { required: true, message: "设备归属水司不能为空", trigger: "blur" }
        // ],
        AreaCode: [
          { required: true, message: "区域名称不能为空", trigger: "change" }
        ],
        SupplierID: [
          { required: true, message: "厂家名称不能为空", trigger: "change" }
        ],
        UserID: [
          { required: true, message: "用户名称不能为空", trigger: "change" }
        ],
        communicateAddress: [
          { required: true, message: "通讯地址不能为空", trigger: "blur" }
        ],
        IMEI: [
          { required: true, message: "IMEI号不能为空", trigger: "blur" }
        ],
        TerminalName: [
          { required: true, message: "设备名称不能为空", trigger: "blur" }
        ],
        TerminalID: [
          { required: true, message: "设备编号不能为空", trigger: "blur" }
        ],
        TerminalIDNew: [
          { required: true, message: "设备编号不能为空", trigger: "blur" }
        ],
        InstallDate: [
          { required: true, message: "安装日期不能为空", trigger: "blur" }
        ],
        Caliber: [
          { required: true, message: "口径大小不能为空", trigger: "change" }
        ],
        TerminalMark: [
          { required: true, message: "表状态不能为空", trigger: "change" }
        ],
        protocolId: [
          { required: true, message: "协议不能为空", trigger: "blur" }
        ],
        IMEINew: [
          { required: true, message: "新IMEI号不能为空", trigger: "blur" }
        ],
      },
      // 地图
      map:{},
      // 定位弹窗参数
      mapdialog: {
        title: '定位',
        open: false,
      },
      // 位置
      position:{
        currentLat: '',
        currentLng: '',
        getLat: '',
        getLng: '',
        newformlng: '',
        newformlat: '',
        oldformlng: '',
        oldformlat: '',
        defaultPosition: []
      },
      TMapURL: 'http://api.tianditu.gov.cn/api?v=4.0&tk=b0948f5ee2a41b57f4c01444e00042ba'
      // defaultPosition: dict.type.default_position
    };
  },
  created() {
    this.getList();
    this.getAreaTree();
    this.getAlldbuser()
  },
  mounted() {
    this.getSelectProtocol()
    // 通过最大显示个数控制展开/折叠
    if (this.maxShow > 0) {
      this.minShowControl()
    }

  },
  watch: {
    // 根据名称筛选区域树
    keyWordName(val) {
      this.$refs.tree.filter(val);
    },
    // AreaName(val){
    //   this.$refs.areatree.filter(val)
    // },
    // UserName(val){
    //   this.$refs.form.filter(val)
    // }
  },
  methods: {
    // 定位对话框打开
    handleMap(){
      this.mapdialog.title = '定位'
      this.mapdialog.open = true
      this.$nextTick(() => {
        this.initMap();
      })
    },
    // 定位对话框关闭
    closeMapDialog(){
      this.mapdialog.open = false
      this.map = new T.Map('mapContent');
    },
    // 初始化地图
    initMap(){
      let pickup;
      let this_ = this
      const init = new Promise((resolve, reject) => {
        if(window.T !== 'undefined') {
            resolve(window.T)
        }
      })
      init.then(T => {
        this_.map = new T.Map('mapContent');
        this_.map.enableDrag()
        let point = new T.LngLat(this.dict.type.default_position[1].value, this.dict.type.default_position[0].value)
        this_.map.centerAndZoom(point, 12);
        this_.map.addOverLay(new T.Marker(point));
        this_.position.currentLat = this.dict.type.default_position[0].value
        this_.position.currentLng = this.dict.type.default_position[1].value
        let config = {
          callback: this_.getLngLat
        };
        pickup = new T.CoordinatePickup(this_.map, config); //获取当前鼠标点击位置的地理坐标
        pickup.addEvent();
      })
    },
    getLngLat(lnglat){
      const x = lnglat.lng;
      const y = lnglat.lat; //纵坐标纬度
      this.map.clearOverLays(); // 清空原来的标注点
      let point = new T.LngLat(x, y);
      let marker = new T.Marker(point);
      this.map.addOverLay(marker); // 添加标注点
      this.getGeocoderFun(x, y);
    },
    // 根据经纬度获取地址
    async getGeocoderFun(lng, lat) {
      let T = window.T;
      let geocoder = new T.Geocoder();
      geocoder.getLocation(new T.LngLat(lng, lat), (result) => {
        this.position.currentLng = lng
        this.position.currentLat = lat
      });
    },
    submitMap(){
      let mapType = 'GAODE'
      // this.gcj2bdString(this.position.currentLng,this.position.currentLat, mapType)
      let positionArr = gcj2bdString(this.position.currentLng,this.position.currentLat, mapType)
      this.form.lng = positionArr[0]
      this.form.lat = positionArr[1]
      this.mapdialog.open = false
    },
    // 表格多选框禁用
    selectable(row, rowIndex){
      if(row.TerminalMark === 1){
        return true;  //不禁用
      }else {
        return false;  //禁用
      }
    },
     //去掉children=null的属性
     normalizer(node){
      if(node.children==null||node.children=='null'){
        delete node.children;
      }
    },
    // 获取协议下拉框中的数据
    getSelectProtocol(){
      let TerminalType = 1
      selectProtocol(TerminalType).then(response => {
        this.protocolOption = response.data
      })
    },
    /** 导入按钮操作 */
    handleImport() {
      this.upload.title = "大用户表导入";
      this.upload.open = true;
    },
    // 文件上传中处理
    handleFileUploadProgress(event, file, fileList) {
      this.upload.isUploading = true;
    },
    // 文件上传成功处理
    handleFileSuccess(response, file, fileList) {
      this.upload.open = false;
      this.upload.isUploading = false;
      this.$refs.upload.clearFiles();
      this.$alert("<div style='overflow: auto;overflow-x: hidden;max-height: 70vh;padding: 10px 20px 0;'>" + response.msg + "</div>", "导入结果", { dangerouslyUseHTMLString: true });
      this.getList();
    },
    // 提交上传文件
    submitFileForm() {
      this.$refs.upload.submit();
    },
    getAlldbuser(){
      getAllUsersdb().then(response => {
        this.usersoptions = response.data
      });
    },
    // 单击下拉框中的数据
    handleSelectTree(data){
      this.selectOptions.label = data.label
      this.selectOptions.value = data.id
      this.form.AreaCode = data.id
    },
    filterValue(query){
      if (query !== "") {
        this.areaOptions = this.areaOptions((item) => {
          if(item.areaName.toLowerCase().indexOf(query) > -1){
            return item
          }
        })
      } else {
        this.areaOptions = [];
      }
    },
    // 展开折叠按钮
    shiftCollapseAble() {
      this.fold = !this.fold
      this.minShowControl()
    },
    // 通过maxShow控制元素显示/折叠
    minShowControl() {
      const group = window.document.querySelectorAll(`#searchFilter .el-form-item.el-form-item--${this.size}`)
      const len = group?.length ? group?.length - 1 : 0
      if (this.maxShow < len) {
        group.forEach((item, index) => {
          if (index > this.maxShow - 1 && index < len) {
            item.hidden = !this.fold
          }
        })
        this.collapseAble = true
      } else {
        this.collapseAble = false
      }
    },
    // 筛选节点
    filterNode(value, data) {
      if (!value) return true;
      return data.label.indexOf(value) !== -1;
    },
    // 节点单击事件
    handleNodeClick(data) {
      this.queryParams.AreaCode = data.id;
      this.handleQuery();
    },
    /** 查询区域下拉树结构 */
    getAreaTree() {
      let list_ = JSON.parse(localStorage.getItem('list'))
      list_.forEach((item) => {
        var obj = {
          id: item.areaCode,
          label: item.areaName,
          children: item.children && item.children.length > 0 ? this.copyTree(item.children) : item.children
        }
        this.areaOptions.push(obj)
      })
    },
    copyTree(list) {
      list.forEach((item) => {
        item.id = item.areaCode;
        item.label = item.areaName;
        item.children = item.children;
        if (item.children && item.children.length) {
          this.copyTree(item.children);
        }
      });
      return list;
    },
    // 改变tree的显示与隐藏
    changeTreeShow(){
      this.treeVisibale =!this.treeVisibale
    },
    init(){
      // 调用接口获取到数据后
      let _self = this
      this.$nextTick(() => {
        window.setTimeout(() => {
          _self.$refs.tableList.doLayout()
        }, 100)
      })
    },
    /** 查询大档案列表 */
    getList() {
      this.init();
      this.loading = true;
      listTerminalsdb(this.queryParams).then(response => {
        this.terminalsdbList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    oncancel() {
      this.openreplace = false;
      this.reset()
    },
    // 表单重置
    reset() {
      this.form = {
        ID: null,
        tenantId: '710170',
        AreaCode: null,
        ldId: null,
        roomId: null,
        SupplierID: null,
        UserID: null,
        TypeID: null,
        TerminalName: null,
        TerminalID: null,
        BaseReading: null,
        InstallDate: null,
        InstallAddress: null,
        IMEI: null,
        SIMtype: null,
        SIMNUM: null,
        PlasticSealNo: null,
        FirstSupplierID: null,
        ValveControl: null,
        ValveAddress: null,
        freezedateMonth: null,
        ManufactureDate: null,
        Caliber: null,
        ReadingFrequency: null,
        UpFrequency: null,
        UserType: null,
        DeleteMark: null,
        ReMark: null,
        TerminalMark: null,
        locationNb: null,
        BaseReadingNew: null,
        IMEINew: null,
        TerminalIDNew: null,
        protocolId: null,
        communicateAddress: null,
        lng: null,
        lat: null,
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      // this.queryParams.TerminalMark = 1
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.ID)
      this.terminalids = selection.map(item => item.TerminalID)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加大用户表档案";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const ID = row.ID || this.ids
      getTerminalsdb(ID).then(response => {
        this.form = response.data;
        let mapType = 'GAODE'
        if(this.form.lng != '' && this.form.lng != null && this.form.lat != '' && this.form.lat != null){
          // this.gcj2bdString(this.form.lng, this.form.lat, mapType)
          let positionArr = gcj2bdString(this.position.currentLng,this.position.currentLat, mapType)
          this.form.lng = positionArr[0]
          this.form.lat = positionArr[1]
        }
        // this.form.lng = this.position.currentLng
        // this.form.lat = this.position.currentLat
        this.open = true;
        this.title = "修改大用户表档案";
      });
    },
    // 换表按钮操作
    handlereplace(row){
      this.reset();
      getTerminalsdb(row.ID).then(response => {
        this.form = response.data;
        this.openreplace = true;
        this.title = "换表";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          let mapType = 'BAIDU'
          if(this.form.lng != '' && this.form.lng != null && this.form.lat != '' && this.form.lat != null){
            // this.gcj2bdString(this.form.lng, this.form.lat, mapType)
            let positionArr = gcj2bdString(this.position.currentLng,this.position.currentLat, mapType)
            this.form.lng = positionArr[0]
            this.form.lat = positionArr[1]
          }
          // this.form.lng = this.position.currentLng
          // this.form.lat = this.position.currentLat
          if (this.form.ID != null) {
            updateTerminalsdb(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addTerminalsdb(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    // 换表提交
    submitReplace(){
      this.$refs["form"].validate(valid => {
        if (valid) {
          // let mapType = 'BAIDU'
          // this.form.lng = this.currentLng
          // this.form.lat = this.currentLat
          if (this.title === '换表') {
            replaceTerminalsdb(this.form).then(response => {
              this.$modal.msgSuccess("换表成功");
              this.openreplace = false;
              this.getList();
            })
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const IDs = row.ID || this.ids;
      const terminalIDs = row.TerminalID || this.terminalids
      this.$modal.confirm('是否确认删除设备编号为"' + terminalIDs + '"的数据项？').then(function() {
        return delTerminalsdb(IDs);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('basedata/terminalsdb/export', {
        ...this.queryParams
      }, `terminalsdb_${new Date().getTime()}.xlsx`)
    }
  }
};
</script>
<style lang="scss" scoped>
  .option {
    height: auto;
    line-height: 1;
    padding: 0;
    background-color: #fff;
  }
  .tree {
    padding: 4px 20px;
    font-weight: 400;
  }
  .form_col{
    width: 80%;
    ::v-deep .el-form {
      width: 100%;
    }
    ::v-deep .el-form-item {
      width: 25%;
    }
  }
  .form_query{
    width: 20%;
    text-align: right;
  }
  .container-box{
    //弹出层的高度
    ::v-deep .el-dialog.import-dialog{
      // height: auto;
      max-height: 80vh;
      overflow: auto;
    }
    //弹出层里内容的高度
    ::v-deep .el-dialog__body{
      max-height: 70vh!important;
      overflow: auto;
    }
  }
  .line{
    height: 500px;
    ::v-deep .el-card__body{
      width: 100%;
      height: 500px;
      background-color: white;
      padding: 0px 0px;
    }
  }
  #mapContent{
    width: 100%;
    margin: 0 auto;
    height: 500px;
  }
</style>
